package com.apexsoft.margin.account.management.util;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * EasyExcel 工具类
 * 处理 EasyExcel.read(file.getInputStream，listener).build;
 * 以文件输入流作为 入参 返回 LinkedHashMap 类型
 */
public class EasyExcelUtil {


    public static <T>List<Map<String,String>> getExcelcontent(MultipartFile file, Class<T> tClass){
        List<Map<String,String>> excelPropertyIndexModeList = new ArrayList<>() ;
        try{
            // 监听器
            AnalysisEventListener<Map<String , String>> listener = new AnalysisEventListener<Map<String , String>>(){

                // 读取一行数据
                @Override
                public void invoke(Map<String, String> excelPropertyIndexModel, AnalysisContext analysisContext) {
                    excelPropertyIndexModeList.add(excelPropertyIndexModel) ;
                    Logger logger = LoggerFactory.getLogger(EasyExcelUtil.class) ;

                    logger.info(GsonUtil.getDefaultGson().toJson(excelPropertyIndexModel));
                    logger.info(GsonUtil.getDefaultGson().toJson(excelPropertyIndexModel.get(0)));
//                    System.out.println(excelPropertyIndexModel);
//                    System.out.println(excelPropertyIndexModel.get(0));

                    // TODO:将每一行被读取的数据存入数据库
                    // 传入数据表名，
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                    // 读取之后的操作

                }
            };

            /**
             * file.getInputStream() 输入流
             * listener 自定义的监听器
             */
            ExcelReader excelReader = EasyExcel.read(file.getInputStream(), listener).build() ;

            // readSheet(0) 指定读取那一页的数据
            ReadSheet sheet = EasyExcel.readSheet(0).build() ;
            excelReader.read(sheet) ;

            excelReader.finish();
        }catch (Exception e){
            e.printStackTrace();
        }

        return excelPropertyIndexModeList ;
    }

}
